package com.study.common.utils;

import com.study.modules.jsoup.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Mr.Du
 * @Date 2021/10/3 10:01
 */
public class JsoupUtils {

    public static List<Content> parseJinDong(String keyword) throws Exception {
        List<Content> list = new ArrayList<>();
        String JinDongUrl = "https://search.jd.com/Search?keyword=" + keyword;
        Document html = Jsoup.parse(new URL(JinDongUrl), 50000);
        Element element1 = html.getElementById("J_goodsList");
        Elements elementList = element1.getElementsByTag("li");
        for (Element element : elementList) {
            String img = element.getElementsByTag("img").get(0).attr("data-lazy-img");
            String price = element.getElementsByClass("p-price").eq(0).text();
            String title = element.getElementsByClass("p-name").eq(0).text();
            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);
            list.add(content);
        }
        return list;
    }

}
